package cn.kgc.springboot.shiro.controller;

import cn.kgc.springboot.shiro.entity.User;
import cn.kgc.springboot.shiro.service.UserService;
import cn.kgc.springboot.shiro.util.SaltUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.security.provider.MD5;

/**
 * @author: mosin
 * @version: v1.0  2023/1/11
 */
@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    // 注册
    @RequestMapping("register")
    public String  register(User user){
        // 密码加密操作  随机salt  增加hash的次数
        String password = user.getPassword();
        String salt = SaltUtil.getSalt(8);
        user.setSalt(salt);

        password = new Md5Hash(password, salt, 50).toHex();
        user.setPassword(password);

        userService.save(user);
        return "redirect:/login.jsp";
    }


    @RequestMapping("login")
    public String  login(User user){
        //  认证  shiro  subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            if(user.getRememberMe()!=null){  // 判定用户是否勾选记住我
                usernamePasswordToken.setRememberMe(true);   //  开启记住我的功能
            }
            subject.login(usernamePasswordToken);
        } catch (IncorrectCredentialsException  e) {
            e.printStackTrace();
            return "redirect:/login.jsp";
        }catch (UnknownAccountException e){
            e.printStackTrace();
            return "redirect:/login.jsp";
        }
        return "redirect:/index.jsp";
    }


    // 添加权限校验   1.编程式  2.注解
    @RequestMapping("delete")
    @RequiresRoles({"admin"})  //  访问该接口时 要有管理员的身份  admin  role
    //@RequiresPermissions({"user:delete"})
    public String  delete(Integer id){
        System.out.println("id = " + id);
        return "redirect:/index.jsp";
    }


    @RequestMapping("update")
    @RequiresRoles({"admin","super"})  //  访问该接口时 要有管理员的身份  admin  role
    public String  update(){
        System.out.println("用户信息被更新");
        return "redirect:/index.jsp";
    }

    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
}
